/*
部署建议：
全局引用zepto.js,g.js,comm.css
各自网站中创建自己的全局JS,和公用css
全局JS中需要申明config对象并申明属性
	root：接口根路径url
	webroot:测试网页接口
	isTest:是否测试（开发为true，上线为false）
	ossroot:oss根路径
如果有多页面共用样式或js请使用独立文件存放，如果各个页面各自独立的js或样式，直接写在页面中
*/
(function () {
    if (window['WeiLai'] || (window.webkit != null && window.webkit.messageHandlers != null && navigator.userAgent.indexOf('MicroMessenger') <= -1)) {
        if (document.getElementsByTagName("header") != null && document.getElementsByTagName("header") != undefined && document.getElementsByTagName("header").length > 0) {
            // $("header").css({
            //     "border-top":"20px transparent solid",
            //     "height":"108px"
            // })
            document.getElementsByTagName("header")[0].style.borderTop = "40px transparent solid";
        }
        if (document.getElementsByTagName("header") != null && document.getElementsByTagName("header") != undefined && document.getElementsByTagName("header").length > 1) {
            document.getElementsByTagName("header")[1].style.borderTop = "40px transparent solid";
        }
    }
}());
var _isTest = false, bootPATH = '';
var __pageinfo = { android_home: 0, wback: [] };
(function (js) {
    var scripts = document.getElementsByTagName("script");
    var path = "";
    for (var i = 0, l = scripts.length; i < l; i++) {
        var src = scripts[i].src;
        if (src.indexOf(js) != -1) {
            var ss = src.split(js);
            path = ss[0];
            break;
        }
    }
    thisPATH = location.href;
    thisPATH = thisPATH.split("#")[0];
    thisPATH = thisPATH.split("?")[0];
    var ss = thisPATH.split("/");
    ss.length = ss.length - 1;
    thisPATH = ss.join("/") + '/';
    if (path.indexOf("https:") == -1 && path.indexOf("http:") == -1 && path.indexOf("file:") == -1 && path.indexOf("\/") != 0) {
        path = thisPATH + path;
    }
    return path;
})("g.js");
var AJAX = {
    Uri: function () {
        return (window['config'] && window['config']['root']) ? config.root : '';
    },
    scanUri: function () {
        //return 'http://39.108.208.186/asba/';
        return (window['config'] && window['config']['scanroot']) ? config.scanroot : '';
    },
    WebRoot: function () {
        return (window['config'] && window['config']['webroot']) ? config.webroot : '';
    },
    K: function () {
        return '__utoken';
    }, P: function () {
        return '_timespan';
    },
    _pind: 0, _psize: 10, _total: 0,
    GET: function (api, cb, err, expcb) {
        var k = AJAX.ab();
        if (k) api += (api.indexOf('?') > 0 ? '&' : '?') + AJAX.P() + '=' + k.c + '&_token=' + k.b;
        $.ajax({
            url: AJAX.Uri() + api, 
            success:function (a) {
                if (a.code == 110) {
                    AJAX.authError && AJAX.authError();
                } else if (a.code == 1) {
                    cb && cb(a);
                } else {
                    expcb ? expcb(a) : Comm.message(a.msg);
                }
            }, 
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                if (textStatus == 'abort' && errorThrown == null) {
                    console.info("出现网页刷新后导致的跨域错误，后续处理")
                } else {
                    AJAX.Err(api);
                }
                err && err();
            }, dataType: 'json'
        });
    },
    POST: function (api, data, cb, expcb) {
        var k = AJAX.ab();
        if (k) {
            if (data == null) data = {};
            data[AJAX.P()] = k.c;
            data['_token'] = k.b;
        }
        $.ajax({
            url: AJAX.Uri() + api, type: 'post', data: data, cache: false,
            success: function (a) {
                if (a.code == 110) {
                    AJAX.authError && AJAX.authError();
                } else if (a.code == 1) {
                    cb && cb(a);
                } else {
                    expcb ? expcb(a) : Comm.message(a.msg);
                }
            },  error: function (XMLHttpRequest, textStatus, errorThrown) {
                if (textStatus=='abort'&&errorThrown==null){
                    console.info("出现网页刷新后导致的跨域错误，后续处理")
                }else {
                    AJAX.Err(api);
                }
            }, dataType: 'json'
        });
    },
    POSTReport: function (api, data, cb, expcb) {
        var k = AJAX.ab();
        if (k) {
            if (data == null) data = {};
            data[AJAX.P()] = k.c;
            data['_token'] = k.b;
        }
        $.ajax({
            url: AJAX.scanUri() + api, type: 'post', data: data, cache: false,
            success: function (a) {
                if (a.code == 110) {
                    AJAX.authError && AJAX.authError();
                } else if (a.code == 1) {
                    cb && cb(a);
                } else {
                  //  expcb ? expcb(a) : Comm.message(a.msg);
                }
            }, error: function () {
                //   AJAX.Err(api);
            }, dataType: 'json',
            contentType: "application/json;charset=utf-8"
        });
    },
    Err: function (a, b, c) {
        Comm.loading();
        Comm.message('服务器异常' + a + b + c, 1);
    },
    setTag: function (a, b) {
        AJAX.ab(a, b);
    },
    isLogin: function () {
        return AJAX.ab() != null;
    },
    authError: function () {
        AJAX.authError = null;

        //记录当前用户token
        var u = User.get();
        if (u && u.customerid && u.token) {
            SysConfig.set("_curToken", u.token);
        }

        SysConfig.set("authError", "1");
        SysConfig.set("userinfo", "");
        Comm.db('__mysearch', '');
        Comm.db("userinfo", "");
        Comm.db("__utoken","");
        SysConfig.set("__utoken","");
        // Comm.db("cart", "");
        // SysConfig.set("cart", "");
        SysConfig.set("_curToken", "");
        Comm.gotop('login.html');
    },
    ab: function (a, b) {
        if (a && b)
            Comm.db(AJAX.K(), a + '_' + b);
        else {
            var k = Comm.db(AJAX.K());
            if (k && k.length > 5) {
                var t = k.split('_');
                if (t.length == 2) {
                    return { a: t[0], b: t[1], c: k }
                }
            }
        }
        return null;
    }
};
var WTP = new function () {
    var t = 'wtp', a = 'wtp-h', b = 'wtp-i', c = 'wtp-f', o = 'wtp-id', ip = 'wtp-data', f = null, tl = {}, it = 1;

    function getFirst(id) {
        if (id == null)
            id = first;
        return tl[id];
    }

    function getObject(element, tag) {
        return $(element).find('[' + tag + ']').removeAttr(tag);
    }

    function getHtml(element, tag) {
        return getObject(element, tag).prop("outerHTML");
    }

    function calc(d, tp) {
        var s = [], ex, k, is;
        if (d && d.length > 0 && tp.e) {
            for (var i = 0; i < d.length; i++) {
                is = tp.i;
                for (var j = 0; j < tp.e.length; j++) {
                    ex = tp.e[j].substr(2, tp.e[j].length - 4);
                    k = (new Function('var item={index:arguments[0]};with(arguments[1]){ return ' + ex + '}'))(i, d[i]);
                    if (k == null) k = '';
                    is = is.replace(tp.e[j], k);
                }
                s.push(is);
            }
        }
        return s.join('');
    }

    function init() {
        $('*[' + t + ']').each(function (i, e) {
            if (f == null)
                f = $(e).attr(t);
            tl[$(e).attr(t)] = {
                box: $(e).removeAttr(t),
                show: false,
                h: getHtml(e, a),
                i: getHtml(e, b),
                f: getObject(e, c),
                e: null
            };
            $(e).html('');
        });
    }

    function fillo(obj) {
        if (obj == null) return;
        var att, va;
        $('*[' + o + ']').each(function (i, e) {
            if (att = $(e).attr(o)) {
                if (va = obj[att])
                    $(e).val(va).html(va);
            }
        });
    }

    function geto(box) {
        var r = {}, att, rt = false;
        if (box.indexOf('#') == -1) box = '#' + box;
        $(box).find('*[' + ip + ']').each(function (i, e) {
            if (att = $(e).attr(ip)) {
                r[att] = $(e).val() || $(e).html();
                rt = true;
            }
        });
        if (rt) return r;
        return null;
    }

    function filli(obj) {
        if (obj == null) return;
        for (var i in obj) {
            $('#' + i).val(obj[i]).html(obj[i]);
        }
    }

    //data数据
    //模板ID
    //是否追加数据，默认为true,false下容器内数据删除后重新填充
    //psb是否追加到队尾，默认为true，只在append=true下生效，
    function show(data, id, append, psb) {
        if (it) {
            init();
            it = 0;
        }
        if (append == null) append = true;
        if (psb == null) psb = true;
        var s = [];
        if (data && data.length > 0 && (tp = getFirst(id))) {
            var first = false;
            if (!tp.show) {
                $(tp.box).html('');
                if (tp.i)
                    tp.e = tp.i.match(/{{[^}]+}}/g);
                tp.show = true;
                first = true;
            }
            if (tp.h != null & (first || !append))
                s.push(tp.h);
            if (tp.i && data != null && data.length > 0) {
                s.push(calc(data, tp));
            }
            if (append && !first && tp.f != null) {
                $(tp.f).remove();
            }
            var html = s.join('');
            if (append) {
                if (psb)
                    html = (tp.box).html() + html;
                else
                    html += (tp.box).html();
            }
            $(tp.box).html(html);
            if (tp.f)
                $(tp.box).append(tp.f);
        }
    }

    return {
        fill: show,
        fillo: fillo,
        geto: geto,
        filli: filli
    };
};

/*响应android返回键,程序可重写此事件，不可重写，则执行默认事件：关闭*/
function androidback() {
    if (__pageinfo.android_home == 0) {
        Comm.close();
    }
    else {
        if (__pageinfo.android_home == 1) {
            __pageinfo.android_home = 2;
            Comm.confirm('您确定要退出应用？', function (a) {
                if (a == 1)
                    Comm.close();
                else
                    __pageinfo.android_home = 1;
            });
        }
    }
}

/*设置android可首页事件*/
function setAndroidHome() {
    __pageinfo.android_home = 1;
}

/*设置android输入框事件，在需要处理的输入框完成后调用即可*/
function setAndroidKeyboard(ele, sheight) {
    (sheight == null) && (sheight = 0);
    if (Comm.weiLai() && !Comm.iOS() && !window.androidKb) {
        window.androidKb = {
            section: null, input: null, f: function (f) {
                window.androidKb.input = f.target;
            }, b: function (b) {
                setTimeout(function () {
                    window.androidKb.input = null;
                }, 300)
            }
        };
        window.keyBoardEvent = function (show, ratio) {
            if (window.androidKb.input && window.androidKb.section) {
                if (show) {
                    var keyboardHeihgt = window.innerHeight * ratio + sheight;
                    var inputBottom = window.innerHeight - window.androidKb.input.getBoundingClientRect().bottom;
                    if (inputBottom < keyboardHeihgt) {
                        window.androidKb.section.style.transform = "translate(0px,-" + (keyboardHeihgt - inputBottom) + "px)";
                    }
                } else {
                    $("input,textarea").blur();
                    window.androidKb.section.style.transform = "translate(0px,0px)";
                }
            }
        };
    }
    if (window.androidKb) {
        window.androidKb.section = ele ? ele : document.getElementsByTagName("section")[0];
        $("input,textarea").unbind(window.androidKb.f).focus(window.androidKb.f);
        $("input,textarea").unbind(window.androidKb.b).blur(window.androidKb.b);
    }
}

/*原生统一回调，系统内置函数*/
function _w9_wcallback(data) {
    var temp = __pageinfo.wback.pop();
    //__pageinfo.wback = null;
    //android back
    if (data && data == 'ANDROID_000000') {
        window['androidback'] && window.androidback();
        return;
    }
    if (temp == null) return;
    var a = data + '';
    if (data.length > 5) {
        var ss = data.charAt(0), ee = data.charAt(data.length - 1);
        if ((ss == '{' && ee == '}') || (ss == '[' && ee == ']')) {
            try {
                a = JSON.parse(data);
            }
            catch (e) {
                a = data + '';
            }
        }
    }
    temp(a);
}

/*页面重新获得焦点，系统内置函数，不可重写，需要注册事件，请在页面声明pageresume*/
function _w9_resume() {
    SysConfig.read(function () {
        var u = User.get();
        if (u && u.customerid && u.token)
            AJAX.setTag(u.customerid, u.token);
        if (SysConfig.get('wifi_img') == 1) {
            Comm.isWiFi(function (a) {
                IsWiFi = a;
                _w9_resume1();
            });
        }
        else
            _w9_resume1();
    });

}

function _w9_resume1() {
    if (window['pageresume'])
        window.pageresume();
    if (__pageinfo.resume) {
        __pageinfo.resume();
        __pageinfo.resume = null;
    }
}

var Comm = new function () {
    function callNative(m, d) {
        if (ios()) {
            var data = { method: m + (d == null ? '' : ':') };
            if (d) data['data'] = dataToString(d);
            window.webkit.messageHandlers.WeiLai.postMessage(data);
        }
        else {
            if (window.WeiLai && (typeof window.WeiLai[m] == typeof function () {
            })) {
                if (d == null)
                    window.WeiLai[m]();
                else
                    window.WeiLai[m](dataToString(d));
            }
        }
    }

    function ios() {
        return window.webkit != null && window.webkit.messageHandlers != null && navigator.userAgent.indexOf('MicroMessenger') <= -1
    }

    function w9() {
        return (window['WeiLai'] || ios());
    }

    function wechat() {
        return navigator.userAgent.indexOf('MicroMessenger') > -1
    }

    function dataToString(o) {
        if (o == null) return '';
        if (typeof (o) == typeof ({}) || typeof (o) == typeof ([])) return JSON.stringify(o);
        return o + '';
    }

    function stringToData(s) {
        var a = s;
        if (s) {
            if (typeof s == typeof {})
                return s;
            if ((s.indexOf('{') == 0 || s.indexOf('[') == 0)) {
                try {
                    a = JSON.parse(s);
                }
                catch (err) {
                    a = s;
                }
            }
        }
        return a;
    }

    var URLIST = '__UrlList';
    //封面背景
    var MainBg = {
        box: null,
        s: false,
        d: 0,
        init: function () {
            if (MainBg.box == null) {
                MainBg.box = document.createElement('DIV');
                MainBg.box.id = 'MainBg';
                $(document.body).prepend(MainBg.box);
                MainBg.box.addEventListener('touchstart', MainBg.noact, false);
                MainBg.box.addEventListener('touchmove', MainBg.noact, false);
            }
        },
        noact: function (e) {
            e.preventDefault();
            return false;
        },
        show: function (s) {
            if (s) {
                MainBg.d++;
                if (!MainBg.s) {
                    MainBg.init();
                    MainBg.s = true;
                    $(MainBg.box).show();
                }
            }
            else {
                MainBg.d--;
                if (MainBg.d <= 0 && MainBg.s) {
                    MainBg.d = 0;
                    MainBg.s = false;
                    $(MainBg.box).hide();
                }
            }
        },
        close: function () {
            MainBg.d = 1;
            MainBg.s = true;
            MainBg.show(false);
        }

    };
    //mess
    var Mess = {
        box: null, show: false,
        init: function () {
            if (Mess.box == null) {
                // $("body").append('<div class="msgbox" id="MessgeBox"><div id="MessgeBoxContent"></div><div id="MessgeBoxButton" class="nowrap"></div></div>');
                Mess.box = document.createElement('DIV');
                Mess.box.id = 'MessgeBox';
                Mess.box.className = 'pop-msg-box';
                Mess.box.innerHTML = '<div id="MessgeBoxContent"></div><div id="MessgeBoxButton" class="nowrap"></div>';
                document.body.appendChild(Mess.box);
            }
        },
        alert: function (mess) {
            Mess.init();
            $('#MessgeBoxContent').attr('class', 'center').html(mess);
            $('#MessgeBoxButton').html('<span class="mbuttonfull" ' + callbackstr(1) + '>确定</span>');
            MainBg.show(true);
            Mess.show = true;
            $(Mess.box).show();
        },
        confirm: function (mess) {
            Mess.init();
            $('#MessgeBoxContent').attr('class', 'tleft').html(mess);
            $('#MessgeBoxButton').html('<span class="mbuttonl"' + callbackstr(0)
                + '>取消</span><span class="mbuttonr"' + callbackstr(1) + '>确定</span>');
            MainBg.show(true);
            Mess.show = true;
            $(Mess.box).show();
        },
        close: function () {
            if (Mess.show) {
                Mess.show = false;
                $(Mess.box).hide();
                MainBg.show(false);
            }
        }
    };
    //message
    var Message = {
        box: null,
        h: 0,
        init: function () {
            if (Message.box == null) {
                Message.box = document.createElement('DIV');
                Message.box.id = 'MessgeBoxT';
                document.body.appendChild(Message.box);
            }
        },
        show: function (mess) {
            clearTimeout(Message.h);
            Message.init();
            Message.box.innerHTML = '<span>' + mess + '</span>';
            $(Message.box).show();
            Message.h = setTimeout(function () {
                $(Message.box).hide();
                _w9_wcallback(1);
            }, 1500);
        }
    };

    //处理统一回调事件
    function _callback(d) {
        if (Mess.show)
            Mess.close();
        _w9_wcallback(d);
    }

    function callbackstr(d) {
        return ' onclick="Comm.callback(\'' + d + '\')"';
    }

    //嵌入弹窗
    var WTD = new function () {
        var t = 'wtd', tl = null, box, cancel = false, bid = 'WTDBOX', cid = 'WTDBOXTD', wid = '_WTDBOX';

        function init() {
            if (tl == null) {
                box = document.createElement('div');
                box.id = bid;
                box.innerHTML = '<div id="' + wid + '"><div id="' + cid + '"></div></div>';
                document.body.appendChild(box);
                tl = {};
                $('*[' + t + ']').each(function (i, e) {
                    tl[$(e).attr(t)] = $(e).removeAttr(t).prop("outerHTML");
                    $(e).remove();
                });
            }
        }

        function show(wtdid, can) {
            init();
            cancel = (can) ? true : false;
            if (tl[wtdid]) {
                Comm.bg(true);
                $('#' + bid).click(function (e) {
                    if (e.target.id == wid && cancel) hide();
                });
                $('#' + cid).html(tl[wtdid]);
                $(box).css('display', 'table');
            }
        }

        function hide() {
            if (box) {
                $('#' + cid).html('');
                $(box).css('display', 'none');
                Comm.bg(false);
            }
        }

        return {
            show: show,
            hide: hide
        };
    };
    //加载层
    var Loading = {
        box: null,
        init: function () {
            if (Loading.box == null) {
                Loading.box = document.createElement('div');
                Loading.box.id = 'loadingbox';
                document.body.appendChild(Loading.box);
            }
        },
        show: function (arg) {
            Loading.init();
            if (arg == null || arg == false) {
                $(Loading.box).hide();
                Comm.bg();
            }
            else {
                //Comm.bg(true);
                if (arg == true || arg == '') arg = '加载中，请稍候...';
                $(Loading.box).html('<span>' + arg + '</span>');
                $(Loading.box).show();
            }
        }
    };
    //地图支持
    var Map = {
        show: function (a) {
            //$('html, body').animate({ scrollTop: 0 });
            //禁止滚动条(默认是没有附加这个样式类的）
            var map = Comm.getmap.map;
            if (Comm.getmap.map == null) {
                $("body").append('<div class="allmap">\
								   <header>\
										<div class="Nav borderBottom NavBar">\
											<div class="barItem_Lf" onclick="Comm.getmap.mapConfirm(false)">\
												<span class="barItem_Custom barItem_backImgBtn"></span>\
											</div>\
											<div class="barItem_Rf">\
												<span class="barItem_Custom" onclick="Comm.getmap.mapConfirm(true,\'' + a + '\')">确认</span>\
											</div>\
											<div class="barItem_title">选择地点</div>\
										</div>\
									</header>\
								   <div class="mapddss"><div id="allmap" style="height:' + (Comm.h - 45) + 'px;"></div></div></div>');
                $(".allmap").show();
                // 百度地图API功能
                Comm.getmap.map = new BMap.Map("allmap");
                map = Comm.getmap.map;
            }
            $(".allmap").show();
            $(window).scrollTop(0);
            $(document.body).toggleClass("html-body-overflow");
            $(window).scrollTop(0);
            if (Comm.getmap.maplng > 0 && Comm.getmap.maplat > 0) {
                var point = new BMap.Point(Comm.getmap.maplng, Comm.getmap.maplat);
                map.centerAndZoom(point, 12);
            } else {
                //30.632825  104.044259  成都
                var point = new BMap.Point(104.044259, 30.632825);
                map.centerAndZoom(point, 12);
            }

            // 添加定位控件
            var geolocationControl = new BMap.GeolocationControl();
            geolocationControl.addEventListener("locationSuccess", function (e) {

            });
            map.addControl(geolocationControl);
            // 添加带有定位的导航控件
            var navigationControl = new BMap.NavigationControl({
                // 靠左上角位置
                anchor: BMAP_ANCHOR_TOP_LEFT,
                // LARGE类型
                type: BMAP_NAVIGATION_CONTROL_LARGE,
                // 启用显示定位
                enableGeolocation: true
            });
            map.addControl(navigationControl);
            var opts = {
                width: 240,     // 信息窗口宽度
                height: 60,     // 信息窗口高度
                title: "请确认地址？", // 信息窗口标题
                enableMessage: true//设置允许信息窗发送短息
            };
            var html = "<div class='address' style='margin-top:10px'></div>";
            /*"<div class='address' style='margin-top:10px'></div><div class='mapconfirm'><span onclick='Comm.mapConfirm(false)'>取消</span><span class='newBtnYes' onclick='Comm.mapConfirm(true,\"" + a + "\")'>确认</span></div>";*/

            //单击获取点击的经纬度
            map.addEventListener("click", function (e) {
                map.clearOverlays();
                var point = new BMap.Point(e.point.lng, e.point.lat);
                var marker = new BMap.Marker(point);// 创建标注
                map.addOverlay(marker);
                Comm.getmap.maplng = e.point.lng;
                Comm.getmap.maplat = e.point.lat;
                var infoWindow = new BMap.InfoWindow(html, opts);  // 创建信息窗口对象
                map.openInfoWindow(infoWindow, point); //开启信息窗口

                var url = 'http://api.map.baidu.com/geocoder/v2/?callback=renderReverse&location=' + Comm.getmap.maplat + ',' + Comm.getmap.maplng + '&output=json&pois=1&ak=LsAGblWKqeWtwRWgmm0AWAm7QAOLW96Y';
                $.ajax({
                    url: url, type: 'post', cache: false,
                    success: function (a) {
                        Comm.getmap.mapaddrs = a.result.formatted_address;//+ a.result.sematic_description;
                        Comm.getmap.province = a.result.addressComponent.province;
                        Comm.getmap.city = a.result.addressComponent.city;
                        Comm.getmap.county = a.result.addressComponent.district;
                        $(".address").html(Comm.getmap.mapaddrs);
                    }, error: function (e) {
                        //Comm.message(e);
                    }, dataType: 'jsonp'
                });
            });
        }
    };
    return {
        g: function (o) {
            return document.getElementById(o);
        },
        query: function (n, u) {
            if (n == null) {
                n = self.location.search;
                if (n && n != "") return n.replace("?", ""); else return null;
            }
            var s = u;
            if (s == null) s = self.location.href;
            if (n) {
                var g = new RegExp("(\\?|&)" + n + "=([^&|#]*)");
                var r = s.match(g);
                if (r) {
                    try {
                        return decodeURIComponent(r[2]);
                    } catch (err) {
                        return unescape(r[2]);
                    }
                } else return null;
            } else {
                var i = s.indexOf("?");
                if (i == -1) return null;
                return s.substr(i + 1);
            }
        },
        /*是否为应用*/
        weiLai: function () {
            return w9();
        },
        /*是否为iOS设备*/
        iOS: function () {
            return ios();
        },
        /*是否为微信*/
        wechat: function () {
            return wechat();
        },
        /*将josn还原为对象*/
        stringToData: stringToData,
        run: function (e) {
            var r = requestAnimationFrame || webkitRequestAnimationFrame || mozRequestAnimationFrame;
            if (r) r(e); else {
                setTimeout(e, 1000 / 60);
            }
            /*16.667*/
        },
        callback: _callback,
        /*公共部分 开始*/
        //新页面
        go: function (url, cb) {
            if (_isTest)
                url = AJAX.WebRoot() + url;
            if (w9()) {
                __pageinfo.resume = cb;
                callNative('go', url);//WeiLai.go(url);
            }
            else {
                var list = Comm.sdb(URLIST);
                if (list == null) list = [];
                list.push(self.location.href);
                Comm.sdb(URLIST, list);
                self.location.href = url;
            }
        },
        //返回栈顶
        gotop: function (url) {
            if (url == null) url = '';
            if (_isTest)
                url = AJAX.WebRoot() + url;
            if (w9()) {
                callNative('gotop', url);
                //WeiLai.gotop(url);
            }
            else {
                if (url == '') {
                    var list = Comm.sdb(URLIST);
                    if (list == null || list.length == 0)
                        return;
                    url = list[0];
                }
                Comm.gocls();
                self.location.href = url;
            }
        },
        //清空缓冲池，仅对微信或电脑版有效
        gocls: function () {
            Comm.sdb(URLIST, []);
        },
        //直接跳转，不弹出新页面
        goself: function (url) {
            if (_isTest)
                url = AJAX.WebRoot() + url;
            self.location.href = url;
        },
        //关闭页面
        close: function () {
            if (w9()) callNative('close');// WeiLai.close();
            else {
                var list = Comm.sdb(URLIST);
                if (list == null || list.length == 0) {
                    Comm.gotop('index.html');
                }
                else {
                    var a = list.pop();
                    Comm.sdb(URLIST, list);
                    self.location.href = a;
                }
            }
        },
        //上传图片
        upimg: function (url, cb) {
            __pageinfo.wback.push(cb);
            if (w9()) callNative('upimg', url)//WeiLai.upimg(url);
            //上传图片
        },
        //扫描地维码
        scanf: function (cb) {
            __pageinfo.wback.push(cb);
            if (w9()) callNative('scanf')//WeiLai.scanf();
        },
        //定位
        position: function (cb) {
            __pageinfo.wback.push(cb);
            if (w9()) callNative('position');//WeiLai.position();
        },
        //从地图上选择点
        selectPosition: function (cb, box) {
            __pageinfo.wback.push(cb);
            if (w9()) callNative('selectPosition');//WeiLai.selectPosition();
            else Map.show(box);
        },
        //分享
        shareUrl: function (jsonObj, cb) {
            if (Comm.wechat()) {
                var shareEle = document.createElement("DIV");
                shareEle.className = "__wechat-share";
                shareEle.innerHTML = "请选择右上角按钮进行分享";
                document.body.appendChild(shareEle);
                setTimeout(function () {
                    shareEle.parentNode.removeChild(shareEle);
                }, 2000);
            } else if (Comm.weiLai()) {
                __pageinfo.wback.push(cb);
                if (w9()) callNative('shareUrl', jsonObj);//WeiLai.shareUrl(dataToString(jsonObj));
            } else {
                Comm.message("当前状态不支持分享");
            }
        },
        //七鱼客服
        qiyu: function (jsonObj, cb) {
            __pageinfo.wback.push(cb);
            if (w9()) callNative('qiyu', jsonObj);//WeiLai.shareUrl(dataToString(jsonObj));
        },
        setPush: function (jsonObj, cb) {
            __pageinfo.wback.push(cb);
            if (w9()) callNative('setPush', jsonObj);//WeiLai.shareUrl(dataToString(jsonObj));
        },
        //网络请求get
        get: function (url, cb) {
            __pageinfo.wback.push(cb);
            if (w9()) callNative('get', url);//WeiLai.get(url);
        },
        //网络请求post
        postData: function (jsonObj, cb) {
            __pageinfo.wback.push(cb);
            if (w9()) callNative('postData', jsonObj);//WeiLai.postData(dataToString(jsonObj));
        },
        //数据保存获取
        storage: function (key, cb) {
            __pageinfo.wback.push(cb);
            if (w9())
                callNative('storage', key);
            else
                cb && cb(Comm.db(key));
            //WeiLai.storage(key);
        },
        //设置缓存数据
        storageValue: function (key, obj, cb) {
            __pageinfo.wback.push(cb);
            if (w9())
                callNative('storageValue', { key: key, value: dataToString(obj) });
            else {
                Comm.db(key, obj);
                cb && cb();
            }
            //WeiLai.storageValue(dataToString(jsonObj));
        },
        //设置背景色
        setbg: function (rgb, cb) {
            __pageinfo.wback.push(cb);
            if (w9()) callNative('setbg', rgb);//WeiLai.setbg(rgb);
        },
        //设置手机转向
        rotate: function (value, cb) {
            __pageinfo.wback.push(cb);
            //1值竖向展示【默认】,	2横向展示
            if (w9()) callNative('rotate', value == 1 ? 1 : 2);//WeiLai.rotate(value==1?1:2);
        },
        //提示框
        alert: function (mess, cb) {
            __pageinfo.wback.push(cb);
            !mess && (mess = "");
            if (w9()) callNative('alert', mess);//WeiLai.alert(dataToString(mess));
            else Mess.alert(mess);
        },
        //确认框
        confirm: function (mess, cb) {
            __pageinfo.wback.push(cb);
            !mess && (mess = "");
            if (w9()) callNative('confirm', mess);//WeiLai.confirm(dataToString(mess));
            else Mess.confirm(mess);
        },
        //提示消息
        message: function (mess, web) {
            // __pageinfo.wback.push(cb);
            (!mess || (mess == "")) && (mess="服务器帮亲淘好货去啦");


            if (w9() && !web){
                callNative('message', mess);//WeiLai.message(mess);
            }else{
                Message.show(mess);
            }
        },
        //判断当前网络是否为wifi环境
        isWiFi: function (cb) {
            if (w9()){
                __pageinfo.wback.push(cb);
                callNative('isWiFi');
            }else{
                cb && cb();
            }
        },
        //清理缓存
        clearCache: function (cb) {
            __pageinfo.wback.push(cb);
            if (w9()) callNative('clearCache');
        },
        //第三方登录 type:凭证类别 1微信，2QQ
        extLogin: function (type, cb) {
            __pageinfo.wback.push(cb);
            if (w9()) callNative('extLogin', type);
        },
        //支付
        pay: function (jsonObj, cb) {
            __pageinfo.wback.push(cb);
            if (w9()) callNative('pay', jsonObj);
        },
        //设备信息
        deviceInfo: function (cb) {
            __pageinfo.wback.push(cb);
            if (w9()) callNative('deviceInfo');
        },
        //获取用户通讯录
        getAddressBook: function (cb) {
            __pageinfo.wback.push(cb);
            if (w9()) callNative('getAddressBook');
        },
        //文本复制
        copyText: function (str) {
            if (w9()) callNative('copyText', str);
        },
        //获取软件版本号
        getVersion: function (cb) {
            __pageinfo.wback.push(cb);
            if (w9()) callNative('getVersion');
        },
        //获取token
        getPushToken: function (cb) {
            __pageinfo.wback.push(cb);
            if (w9()) callNative('getPushToken');
        },
        //打开外部浏览器
        openUrlStr: function (url) {
            if (w9())
                callNative('openUrlStr', url);
            else
                location.href = url;
        },
        getQQwx: function (type, cb) {
            __pageinfo.wback.push(cb);
            if (w9()) callNative('isExt',type);
        },
        OSS: {
            /*阿里云oss工具*/
            host: function () {
                return window['config'] && window.config['ossroot'] ? config.ossroot : '';
            }, /*oss访问地址*/
            /*
            获取图片访问地址
            uri:数据库中保存的文件地址
            type:显示类型 	取值:s|m|l
            canwifi:忽略wifi设置
             */
            getImgUrl: function (uri, type, canwifi) {
                if (IsWiFi == 0 && !canwifi)
                    return 'img/wifiimg.png';
                if (uri == null)
                    return "img/errorgoods.png";
                if (uri.length >= 4 && uri.indexOf("//") > -1)
                    return uri;
                var url = Comm.OSS.host() + uri;
                if (type) {
                    url += webpSupport ? "/w" : "/";
                    switch (type) {
                        case 'l':
                            url += '800';
                            break;
                        case 'f':
                            url += '480';
                            break;
                        case 'm':
                            url += '250';
                            break;
                        case 's':
                            url += '120';
                            break;
                    }
                }
                return url;
            }
        },
        /*公共部分 结束*/
        bg: function (show, cls) {
            if (cls)
                MainBg.close();
            else
                MainBg.show(show);
        },
        /*wtdid:模板id ,<div id="sinbox" wtd="模板ID"></div>
        cancel：点击背景是否可以取消*/
        showWindow: function (wtdid, cancel) {
            if (wtdid) WTD.show(wtdid, cancel); else WTD.hide();
        },
        /*s相当于localStorage 如果有回调效果，请使用SysConfig*/
        db: function (t, v) {
            if (v == null) {
                if (arguments.length == 1) {
                    return stringToData(window.localStorage[t]);
                } else {
                    window.localStorage.removeItem(t);
                }
            } else {
                window.localStorage[t] = dataToString(v);
            }
            if (ios())
                callNative("syncData", { name: t, value: v });
        },
        /*主动弹出加载效果
        arg,显示文字，如果不传入则表示关闭 */
        loading: function (arg) {
            Loading.show(arg);
        },
        /*相当于sessionStorage  如果有回调效果，请使用SysConfig*/
        sdb: function (t, v) {
            if (v == null) {
                return stringToData(window.sessionStorage[t]);
            }
            window.sessionStorage[t] = dataToString(v);
        },
        _loadjs: function (src, func) {
            !func && (func = function () {
            });
            //判断这个js文件存在直接执行回调
            var scripts = document.getElementsByTagName('script');
            for (var i in scripts)
                if (scripts[i].src && scripts[i].src.indexOf(src) > -1)
                    return func();
            if (typeof func != 'function') return false;
            var script = document.createElement('script');
            script.type = 'text/javascript';
            script.src = src;
            var head = document.getElementsByTagName('head').item(0);
            head.appendChild(script);
            script.onload = function () {
                func();
            }
        },
        log: function (v) {
            if (v == typeof ({})) {
                var s = [];
                for (var i in v)
                    s.push(i + ':' + v[i]);
                v = s.join('\n');
            }
            console.log(v);
        }
    }
};
//本地配置
var SysConfig = new function () {
    var o = null, name = "__SysConfig";

    /*如果key为空则返回配置完整对象，注意为对象引用，对原始对象更新后注意及时set，保存*/
    function get(key) {
        if (o == null)
            return null;
        else {
            if (key)
                return o[key];
            else
                return o;
        }
    }

    /*如果参数为空，则直接保存原始对象而不是单值*/
    function set(key, value) {
        if (o == null) {
            return false;
        }
        if (key) o[key] = value;
        if (Comm.weiLai()) {
            Comm.storageValue(name, o, null);
        }
        else {
            Comm.db(name, o);
        }
        return true;
    }

    function init(data) {
        if (data == null || data == "")
            o = {};
        else
            o = Comm.stringToData(data);
    }

    function read(cb) {
        if (Comm.weiLai()){
            Comm.storage(name, function (data) {
                init(data);
                cb && cb();
            });
        }else{
            init(Comm.db(name));
            cb && cb();
        }
    }

    return {
        /*get(key),如果不存在或未执行reead,返回null*/
        get: get,
        /*set(key,value),如果未执行read将返回false,正常执行返回true*/
        set: set,
        /*read(cb)需要使用本地存储必须先使用read方法，建议在页面初始化时调用，调用一次即可，如果页面回调，请重新调用*/
        read: read
    }
};

function showreload() {
    $(document.body).append('<button style="z-index:999999;position:fixed;top:55px;right:5px;" onclick="document.location.reload()">刷新</button>');
}

var webpSupport = parseInt(Comm.db("webpSupport"));
if (isNaN(webpSupport)) {
    webpSupport = document.createElement('canvas').toDataURL('image/webp').indexOf('data:image/webp') === 0;
    Comm.db("webpSupport", webpSupport ? "1" : "0");
}
var IsWiFi = 1;
window.onload = function () {
    if (window['config'] && config['isTest'] != null) _isTest = !!config['isTest'];
    if (_isTest) {
        showreload();
        window.onerror = function (e) {
            Comm.alert('脚本错误:' + e);
        }
    }
    // if(Comm.weiLai()) {
    // 	$("header").addClass("pt20");
    // }
    resizeSection();
    window.onresize = resizeSection;
    //加载缓存
    SysConfig.read(function () {
        if (Comm.weiLai()) {
            var u = User.get();
            if (u && u.customerid && u.token)
                AJAX.setTag(u.customerid, u.token);
        }
        IsWiFi = 1;
        if (SysConfig.get('wifi_img') == 1) {
            Comm.isWiFi(function (a) {
                IsWiFi = a;
                window['pageload'] && window.pageload();
            });
        }
        else
            window['pageload'] && window.pageload();
    });
    setTimeout(function () {
        window.onresize = null;
    }, 500);
};

function resizeSection(e) {
    // var h = document.querySelector('body >header'), f = document.querySelector('body >footer'),
    //     s = document.querySelector('body >section');
    // //if (f) f.style.position = "relative";
    // if (s) {
    //     s.style.height = window.innerHeight - (h ? h.offsetHeight : 0) - (f ? f.offsetHeight : 0) + 'px';
    // }
    var wh = $(window).height();
    var th = $("header").height() ? $("header").height() : 0;
    var fh = $("footer").height() ? $("footer").height() : 0;
    $("section").css({
        "height": (wh - th - fh)
    });
}
//--------------------------------------------------------------------------------------------------------------------------------------------//
//打点数据
$(function () {
    function async_load() {
        var cnzz_s_tag = document.createElement('script');
        cnzz_s_tag.type = 'text/javascript';
        cnzz_s_tag.async = true;
        cnzz_s_tag.defer = true;
        cnzz_s_tag.charset = "utf-8";
        cnzz_s_tag.src = "//s19.cnzz.com/z_stat.php?id=1271593815&web_id=1271593815&async=1";
        var root_s = document.getElementsByTagName('script')[1];
        root_s.parentNode.insertBefore(cnzz_s_tag, root_s);
    }
    if (window.attachEvent){
        window.attachEvent('onload', async_load);
    }else{
        window.addEventListener('load', async_load, false);
    }

});

//自定义打点数据
function monitoringCBI(url, data) {

    //获取uuid
    var guuid = Comm.db('guid');
    if (typeof (guuid) == "undefined") {
        guuid = guid();
        Comm.db('guid', guuid);
    }

    //获取注册TYpe
    var regTypeId = Comm.db('regTypeId');
    if (typeof (regTypeId) == "undefined") {
        regTypeId = '';
    }
    //获取用户ID；
    var userInfo = Comm.db('userinfo');
    var userId;
    if (typeof (userInfo) === "undefined") {
        userId = ''
    } else {
        userId = userInfo.customerid;
    }


    var pData = {};
    //生成所需要的打点数据
    $(data).each(function (n, v) {
        if (v === 'userid') {
            pData.uid = userId;
        }
        if (v === 'uuid') {
            pData.identification = guuid;
        }
        if (v === 'date') {
            pData.date = new Date().getTime();
        }
        if (v === 'type') {
            pData.type = regTypeId;
        }
    });

    AJAX.POSTReport(url, JSON.stringify(pData), function (r) { })

}



//UUID生成器
function guid() {
    return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
        var r = Math.random() * 16 | 0, v = c == 'x' ? r : (r & 0x3 | 0x8);
        return v.toString(16);
    });
}

//响应七鱼的推送消息
function _w9_reActive(msg) {
    Comm.db("kf",1);
    qiyu();
}

showMsgPoint(); //
function showMsgPoint() { //显示右上角客服红点
//  var kf = Comm.db("kf")?true:false;
//  if(kf && $("header .icon-msg").length>0){
//      $("header .icon-msg").addClass("active");
//  }

}

//
noBodySelect()
function noBodySelect(){
    if( $("input").length<=0 && $("textarea").length<=0   ){
        $("body").addClass("bodynosel");
    }
}


// Comm.getQQwx(2, function(a) {
//     alert(JSON.stringify(a));//返回值{"wx":true};
// });

// Comm.getQQwx(1, function(a) {
//     alert(JSON.stringify(a));//返回值{"mqq":true};
// });